extends Control

@onready var back_btn : Button = $ColorRect/MarginContainer/VBoxContainer/HBoxContainer/BackBtn
@onready var catalog_name_lbl : Label = $ColorRect/MarginContainer/VBoxContainer/HBoxContainer/CatalogNameLbl
@onready var catalog_name_le : LineEdit = $ColorRect/MarginContainer/VBoxContainer/ColorRect/CenterContainer/VBoxContainer/HBoxContainer/fields/CatalogNameLE
@onready var dec_number_le : LineEdit = $ColorRect/MarginContainer/VBoxContainer/ColorRect/CenterContainer/VBoxContainer/HBoxContainer/fields/DecimalNumberLE
@onready var descr_te : TextEdit = $ColorRect/MarginContainer/VBoxContainer/ColorRect/CenterContainer/VBoxContainer/HBoxContainer/fields/TextEdit
@onready var save_btn : Button = $ColorRect/MarginContainer/VBoxContainer/ColorRect/CenterContainer/VBoxContainer/Button


func _ready():
	if not ENV.current_catalog_data.is_empty():
		catalog_name_le.text = ENV.current_catalog_data["alias"]
		dec_number_le.text = str(ENV.current_catalog_data["decimal_id"]) if ENV.current_catalog_data["decimal_id"] > 9 else str(0, ENV.current_catalog_data["decimal_id"])
		descr_te.text = ENV.current_catalog_data["description"]
	
	back_btn.pressed.connect(_go_to_preferences_page)
	dec_number_le.text_changed.connect(_on_dec_num_edit)
	save_btn.pressed.connect(_on_save_changes)

func _input(event):
	if event.is_action_pressed("ui_cancel"):
		_go_to_preferences_page()

func _go_to_preferences_page():
	get_tree().change_scene_to_file("res://preferences_page/preferences_page.tscn")

func _on_dec_num_edit(input:String):
	var regexp := RegEx.new()
	regexp.compile("^[0-9]{1,2}$")
	if not regexp.search(input):
		dec_number_le.delete_char_at_caret()

func _on_save_changes():
	var result : Dictionary = {}
	
	result["alias"] = catalog_name_le.text
	result["decimal_id"] = int(dec_number_le.text)
	result["description"] = descr_te.text
	
	ENV.current_catalog_data = result
	_go_to_preferences_page()
